package middleware

import (
	"github.com/gin-gonic/gin"
	"go-web-admin/jwt"
	"net/http"
	"strings"
)

// JWTAuthMiddleware JWT认证中间件
func JWTAuthMiddleware(c *gin.Context) {

	// 获取不需要权限校验的URL
	noAuthUrls := jwt.JwtConf.NoAuthUrls
	// 获取请求地址
	path := c.Request.URL.Path

	// 判断请求地址是否包含在不需要校验的URL中
	for _, url := range noAuthUrls {
		if path == url {
			c.Next()
			return
		}
		//if strings.Contains(path, url) {
		//	c.Next()
		//	return
		//}
	}

	// 从请求头中获取token
	authHeader := c.Request.Header.Get("Authorization")
	if authHeader == "" {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  "请求头中auth为空",
		})
		c.Abort()
		return
	}

	// 按空格分割
	parts := strings.SplitN(authHeader, " ", 2)
	if !(len(parts) == 2 && parts[0] == "Bearer") {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  "请求头中auth格式有误",
		})
		c.Abort()
		return
	}

	// 解析token
	claims, err := jwt.ParseToken(parts[1])
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  "无效的Token",
		})
		c.Abort()
		return
	}

	// 将用户信息存入上下文
	c.Set("userId", claims.UserId)
	c.Next()
}
